package com.itheima.d6_tcp3;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

public class Client {
    private static String MSG="";

    public static void main(String[] args) throws IOException {
        Scanner sc = new Scanner(System.in);
        //客户端对象
        Socket client = new Socket("127.0.0.1", 8888);

        //构建一个子线程，专门用来接收服务端发送的信息
        new Thread(()->{
            try {
                //子线程中完成接收数据
                InputStream netIn = client.getInputStream();
                //包装为一个数据流
                DataInputStream dataIn = new DataInputStream(netIn);

                while (!MSG.equals("886")) {//如果当前用户输入的是886
                    try {
                        String msg = dataIn.readUTF();//读取服务端发送的数据
                        System.out.println("服务端发送的数据：" + msg);
                    } catch (IOException e) {
                        System.out.println("读取有误");
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }


        }).start();


        while (true) {
            //获取输出流发信息
            OutputStream netOut = client.getOutputStream();
            DataOutputStream dataOut = new DataOutputStream(netOut);
            System.out.println("输入发送的信息：");
            String msg = sc.nextLine();//阻塞让用户输入信息
            //把输入的信息给到静态变量MSG
            MSG = msg;
            dataOut.writeUTF(msg);

            if (msg.equals("886")) {
                break;
            }

            //获取输入流收信息

        }

        client.close();
    }
}